package com.hsbc.dev.teamo4.sms.sm.dao.impl;

import com.google.common.collect.Lists;
import com.hsbc.dev.teamo4.sms.common.utils.data.DBUtil;
import com.hsbc.dev.teamo4.sms.sm.dao.IDepartmentDao;
import com.hsbc.dev.teamo4.sms.sm.po.Department;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import java.util.List;
import java.util.Map;

/**
 * @author:Kevin
 * @version:
 * @Project: permission_manage
 * @Package: com.hsbc.dev.teamo4.sms.sm.dao.impl
 * @Description:
 * @Date date: 2018/7/28
 */
public class DepartmentDaoImpl implements IDepartmentDao {

    @Override
    public Department saveEntity(Department department) {
        String sql="insert into sm_department values(?,?,?,?,?,?,?,?)";
        return (Department) DBUtil.saveEntity(sql,department,null);
    }

    @Override
    public Department updateEntity(Department department) {
        String sql="update  sm_department set  departmentName=?,departmentParentId=?,departmentLevel=?,departmentOrder=?,updateId=?,updateTime=?,isEnable=? where id=?";
        return (Department) DBUtil.updateEntity(sql,department, Lists.newArrayList("id","createId","createTime"),department.getId());

    }

    @Override
    public int updateByIsEnable(String id, Boolean bool) {
        String sql = "update sm_department set isEnable=? where id=?";
        return DBUtil.updateByIsEnable(sql,id,bool);
    }

    @Override
    public Department queryById(String id) {
        String sql="select * from sm_department where id='"+id+"'";
        BeanHandler beanHandler=new BeanHandler<>(Department.class);
        return (Department) DBUtil.queryById(sql,beanHandler);
    }

    @Override
    public List<Department> queryAllEntity() {
        String sql="select * from sm_department where isEnable='"+true+"'";
        BeanListHandler beanListHandler=new BeanListHandler<>(Department.class);
        return (List<Department>) DBUtil.queryAllEntity(sql,beanListHandler);
    }


    @Override
    public List<Department> getChildDepartmentListByLevel(String level) {
        String sql="select * from sm_permission where departmentLevel like '"+level+"' || '.%'";
        BeanListHandler beanListHandler=new BeanListHandler<>(Department.class);
       return (List<Department>) DBUtil.queryAllEntity(sql,beanListHandler);
    }

    @Override
    public void batchUpdateLevel(List<Department> departments) {
        for (Department department:departments){
            updateEntity(department);
        }
    }

    @Override
    public Map countByNameAndParentId(String parentId, String departmentName, String departmentId) {
        String sql="select count(1) from sm_permission where departmentParentId='"+parentId+"' and '"+departmentName+"' and'"+departmentId+"'";
        MapHandler mapHandler=new MapHandler();
        return (Map) DBUtil.countAndToMap(sql,mapHandler);
    }
}
